package com.ryan.plugin;

import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.List;

class ChooseDialog extends DialogWrapper {

    List<JCheckBox> checkBoxes = new ArrayList<>();
    List<VirtualFile> vfs;
    OnConfirm onConfirm;

    protected ChooseDialog(@Nullable Project project, List<VirtualFile> vfs, OnConfirm onConfirm) {
        super(project, true);
        this.vfs = vfs;
        this.onConfirm = onConfirm;

        init();
        setTitle("Choose Modules");
    }

    @Override
    protected @Nullable
    JComponent createCenterPanel() {
        JPanel content = new JPanel(new GridLayout(vfs.size(), 1));
        for (VirtualFile vf : vfs) {
            JCheckBox checkBox = new JCheckBox(vf.getName(), null, true);
            checkBoxes.add(checkBox);
            content.add(checkBox);
        }

        return content;
    }

    @Override
    public void doCancelAction() {
        super.doCancelAction();
    }

    @Override
    protected void doOKAction() {
        super.doOKAction();
        List<VirtualFile> selected = new ArrayList<>();
        for (int i = 0; i < checkBoxes.size(); i++) {
            if (checkBoxes.get(i).isSelected()) selected.add(vfs.get(i));
        }
        if (this.onConfirm != null) this.onConfirm.confirm(selected);
    }

    interface OnConfirm {
        void confirm(List<VirtualFile> selected);
    }
}
